package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    //redis 缓存
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐
     **/
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("{}", setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
        String key = "setmeal_" + setmealDto.getCategoryId() + "_" + setmealDto.getStatus();
        redisTemplate.delete(key);
        return R.success("添加套餐成功");
    }

    /**
     * 套餐分页查询
     *
     * @return
     **/
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //分页构建器
        Page<Setmeal> pageinfo = new Page(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
        lqw.like(name != null, Setmeal::getName, name);
        lqw.orderByAsc(Setmeal::getCreateTime).orderByAsc(Setmeal::getUpdateTime);

        setmealService.page(pageinfo, lqw);
        //拷贝信息
        BeanUtils.copyProperties(pageinfo, dtoPage, "records");
        List<Setmeal> records = pageinfo.getRecords();

        List<SetmealDto> list = records.stream().map((item) -> {
            Long categoryId = item.getCategoryId();
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            Category category = categoryService.getById(categoryId);


            if (category != null) {
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 根据ID查询对应的套餐信息
     **/
    @GetMapping("/{id}")
    public R<SetmealDto> getByid(@PathVariable Long id) {
        //得到套餐的基础信息
        SetmealDto byidWithDish = setmealService.getByidWithDish(id);

        return R.success(byidWithDish);
    }

    /**
     * 修改套餐信息
     **/
    @PutMapping
    public R<String> updateByid(@RequestBody SetmealDto setmealDto) {
        log.info("{}", setmealDto.toString());
        setmealService.updateByidWithDish(setmealDto);
//这个删除缓存不严谨  因为修改时可能会修改套餐分类
//        String key = "setmeal_"+setmealDto.getCategoryId()+"_"+setmealDto.getStatus();
//        redisTemplate.delete(key);

        Set key = redisTemplate.keys("setmeal_");
        redisTemplate.delete(key);
        return R.success("修改套餐信息成功");


    }

    /**
     * 套餐的批量启停
     **/
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable("status") Integer status, @RequestParam List<Long> ids) {
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper();
        lqw.in(Setmeal::getId, ids);
        setmealService.update(setmeal, lqw);
        return R.success("修改套餐状态成功");
    }

    /**
     * 套餐的批量删除
     **/
    @DeleteMapping
    public R<String> deleteByids(@RequestParam List<Long> ids) {
        log.info("{}", ids.toString());
        setmealService.removeWithDish(ids);
        //删除套餐的缓存S
        Set key =redisTemplate.keys("setmeal_");
        redisTemplate.delete(key);
        return R.success("删除套餐成功");
    }

    /**
     * 对套餐的分类查询
     **/
    @GetMapping("/list")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        // log.info(setmeal.toString());
        //   Long categoryId = setmeal.getCategoryId();
        List<Setmeal> list = null;

        String key ="setmeal_"+setmeal.getCategoryId()+"_"+setmeal.getStatus();

        list =( List<Setmeal>) redisTemplate.opsForValue().get(key);
        if (list!=null){
            //存在缓存直接返回
            return  R.success(list);
        }

        LambdaQueryWrapper<Setmeal> lqw = new LambdaQueryWrapper<>();
        lqw.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        lqw.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        lqw.orderByAsc(Setmeal::getUpdateTime);

        list = setmealService.list(lqw);
        return R.success(list);
    }
}